<template>
  <div class="abnormal-behavior-alarm bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-4">异常行为报警管理</h2>

    <div class="search-form bg-card text-card-foreground p-4 mb-4 rounded shadow">
      <!-- <div class="flex flex-wrap gap-4">
        <div class="flex-1">
          <label for="incidentCode" class="block text-sm font-medium text-muted-foreground">事件编码：</label>
          <input id="incidentCode" v-model="search.code" type="text" placeholder="请输入" class="input" />
        </div>
        <div class="flex-1">
          <label for="incidentType" class="block text-sm font-medium text-muted-foreground">事件类型：</label>
          <select id="incidentType" v-model="search.type" class="input">
            <option value="">全部</option>
            <option value="一般事件">一般事件</option>
            <option value="紧急事件">紧急事件</option>
            <option value="重大事件">重大事件</option>
          </select>
        </div>
        <div class="flex-1">
          <label for="startTime" class="block text-sm font-medium text-muted-foreground">时间日期：</label>
          <input id="startTime" v-model="search.startTime" type="datetime-local" class="input" />
        </div>
        <div class="flex-1">
          <label for="endTime" class="block text-sm font-medium text-muted-foreground">结束时间：</label>
          <input id="endTime" v-model="search.endTime" type="datetime-local" class="input" />
        </div>
        <div class="flex items-end space-x-2">

          <button @click="resetSearch" class="btn btn-secondary">重置</button>
          <button @click="searchIncidents" class="btn btn-primary">查询</button>
        </div>
      </div> -->
      <!-- <query-form :model="search" :formItems="formItems" @search="searchIncidents" @reset="resetSearch" /> -->
      <el-form :inline="true" :model="search" class="query-form-inline">
        <!-- <el-form-item label="开始时间：">
          <input type="datetime-local" v-model="search.TIME_BEGIN"
            class="input-time-query mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
        </el-form-item>
        <el-form-item label="结束时间：">
          <input type="datetime-local" v-model="search.TIME_END"
            class="input-time-query mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
        </el-form-item> -->
        <el-form-item label="时间选择：">
          <input type="datetime-local" v-model="search.START_TIME"
            class="input-time-query mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />&nbsp;&nbsp;
          ——&nbsp;&nbsp;<input type="datetime-local" v-model="search.END_TIME"
            class="input-time-query mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
        </el-form-item>
        <el-form-item label="车辆/人员详情：">
          <el-input v-model="search.CAR_PERSON" placeholder="请输入" />
        </el-form-item>
        <el-form-item class="query-btns">
          <el-button @click="resetSearch" style="width: 75px; height: 30px;">重置</el-button>
          <el-button type="primary" @click="searchIncidents" style="width: 75px; height: 30px;">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="action-buttons bg-card text-card-foreground p-4 mb-4 rounded shadow">
      <div class="flex justify-between items-center">
        <div class="flex space-x-2">
          <!-- <button @click="openAddDialog" class="btn btn-primary">新增</button> -->
          <!-- <button @click="deleteSelected" class="btn btn-destructive">删除</button> -->
          <!-- <button @click="openImportDialog" class="btn btn-secondary">导入</button> -->
          <!-- <button @click="exportData" class="btn btn-secondary">导出</button> -->
          <el-button @click="deleteSelected" style="width: 75px; height: 30px;">删除</el-button>
          <el-button @click="exportData" style="width: 75px; height: 30px;">导出</el-button>
        </div>
        <!-- <button @click="openHandleDialog" class="btn btn-primary">
          设置
        </button> -->
        <el-button type="primary" @click="openHandleDialog" style="width: 75px; height: 30px;">设置</el-button>
      </div>
    </div>

    <div class="data-table bg-card text-card-foreground shadow-md rounded-lg overflow-hidden">
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-border">
          <thead>
            <tr class="bg-muted">
              <th class="table-header w-[60px]">
                <input type="checkbox" :checked="allChecked" @change="toggleAllCheckboxes" class="checkbox" />
              </th>
              <th class="table-header">序号</th>
              <th class="table-header">事件描述</th>
              <th class="table-header">车辆/人员详情</th>
              <th class="table-header">抓拍画面</th>
              <th class="table-header">视频</th>
              <th class="table-header">发生日期</th>
              <!-- <th class="table-header">处理状态</th>
              <th class="table-header">身份验证失败报警</th>
              <th class="table-header">失败尝试次数限制</th>
              <th class="table-header">不按规定时间进出报警</th>
              <th class="table-header">禁止进出开始时间</th>
              <th class="table-header">禁止进出结束时间</th>
              <th class="table-header">频繁进出报警</th>
              <th class="table-header">频繁进出时间间隔(分钟)</th>
              <th class="table-header">频繁进出次数</th>
              <th class="table-header">停留异常报警</th>
              <th class="table-header">停留时间上限(分钟)</th>
              <th class="table-header">操作</th> -->
            </tr>
          </thead>
          <tbody class="divide-y divide-border">
            <tr v-for="(item, index) in displayedIncidentData" :key="item.id" class="hover:bg-muted/50">
              <td class="table-cell w-[60px]">
                <input type="checkbox" v-model="item.checked" class="checkbox" />
              </td>
              <td class="table-cell">{{ startIndex + index + 1 }}</td>
              <td class="table-cell">{{ item.DESCRIPTION }}</td>
              <td class="table-cell">{{ item.CAR_PERSON }}</td>
              <td class="table-cell">{{ item.PASS_CORD }}</td>
              <td class="table-cell">{{ item.PASS_TV ? item.PASS_TV : '无' }}</td>
              <td class="table-cell">{{ formatDateTime(item.TIME_BEGIN) }}</td>
              <!--    <td class="table-cell">{{ item.status }}</td>
              <td class="table-cell">{{ item.id_card_failure_alarm ? '是' : '否' }}</td>
              <td class="table-cell">{{ item.failure_attempts }}</td>
              <td class="table-cell">{{ item.time_restriction_alarm ? '是' : '否' }}</td>
              <td class="table-cell">{{ formatTime(item.restricted_start_time) }}</td>
              <td class="table-cell">{{ formatTime(item.restricted_end_time) }}</td>
              <td class="table-cell">{{ item.frequent_access_alarm ? '是' : '否' }}</td>
              <td class="table-cell">{{ item.frequent_interval }}</td>
              <td class="table-cell">{{ item.frequent_times }}</td>
              <td class="table-cell">{{ item.long_stay_alarm ? '是' : '否' }}</td>
              <td class="table-cell">{{ item.stay_time_limit }}</td>
              <td class="table-cell">
                <button @click="editIncident(item)" class="action-button mr-2">编辑</button>
                <button @click="viewDetails(item)" class="action-button">查看</button>
              </td> -->
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <div class="pagination bg-card text-card-foreground p-4 mt-4 flex items-center justify-between">
      <div>
        <p class="text-sm text-muted-foreground">
          共 <span class="font-medium">{{ totalItems }}</span> 条
        </p>
      </div>
      <div>
        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
          <button @click="prevPage" :disabled="currentPage === 1" class="btn-pagination">
            上一页
          </button>
          <button v-for="page in totalPages" :key="page" @click="goToPage(page)"
            :class="['btn-pagination', currentPage === page ? 'bg-primary text-primary-foreground' : 'bg-card text-card-foreground hover:bg-muted']">
            {{ page }}
          </button>
          <button @click="nextPage" :disabled="currentPage === totalPages" class="btn-pagination">
            下一页
          </button>
        </nav>
      </div>
    </div>

    <!-- 处置对话框 -->
    <!-- <Teleport to="body">
      <div v-if="isHandleDialogOpen"
        class="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
        <div class="bg-card text-card-foreground p-5 rounded-lg shadow-xl w-[800px]">
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-bold">异常行为报警设置</h3>
            <button @click="closeHandleDialog" class="text-muted-foreground hover:text-foreground">
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"
                xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>
          <div class="space-y-4">
            <div>
              <label class="flex items-center space-x-2">
                <input type="checkbox" v-model="handleSettings.idCardFailure" class="checkbox">
                <span>身份验证失败报警</span>
              </label>
              <div class="clselect ml-6">
                <div class="text-sm">事件类型：</div>
                <el-select v-model="value" placeholder="Select" style="width: 240px">

                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </div>
              <div class="ml-6 mt-2" style="display: flex; align-items: center;">
                <label class="block text-sm font-medium text-muted-foreground">失败尝试次数限制：</label>
                <input type="number" v-model="handleSettings.failureAttempts" style="widht:100px !important;" min="1">
                <label class="ml-2">次</label>
              </div>
            </div>
            <div>
              <label class="flex items-center space-x-2">
                <input type="checkbox" v-model="handleSettings.timeRestriction" class="checkbox">
                <span>不按规定时间进出报警</span>
              </label>
              <div class="clselect ml-6">
                <div class="text-sm">事件类型：</div>
                <el-select v-model="value" placeholder="Select" style="width: 240px">

                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </div>
              <div class="ml-6 mt-2 flex items-center space-x-2">
                <label class="text-sm font-medium text-muted-foreground">设置禁止进出时间：</label>
                <input type="time" v-model="handleSettings.startTime" class="input">
                <span>到</span>
                <input type="time" v-model="handleSettings.endTime" class="input">
              </div>
            </div>
            <div>
              <label class="flex items-center space-x-2">
                <input type="checkbox" v-model="handleSettings.frequentAccess" class="checkbox">
                <span>频繁进出报警</span>
              </label>
              <div class="clselect ml-6">
                <div class="text-sm">事件类型：</div>
                <el-select v-model="value" placeholder="Select" style="width: 240px">

                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </div>
              <div class="ml-6 mt-2 flex items-center space-x-2">
                <label class="text-sm font-medium text-muted-foreground">设置频繁进出时间间隔：</label>
                <input type="number" v-model="handleSettings.frequentInterval" class="input" min="1">
                <label>分钟之内超过</label>
                <input type="number" v-model="handleSettings.frequentTimes" class="input" min="1">
                <label>次</label>
              </div>
            </div>
            <div>
              <label class="flex items-center space-x-2">
                <input type="checkbox" v-model="handleSettings.longStay" class="checkbox">
                <span>停留异常报警</span>
              </label>
              <div class="clselect ml-6">
                <div class="text-sm">事件类型：</div>
                <el-select v-model="value" placeholder="Select" style="width: 240px">

                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </div>
              <div class="ml-6 mt-2 flex items-center space-x-2">
                <label class="text-sm font-medium text-muted-foreground">停留时间上限：</label>
                <input type="number" v-model="handleSettings.stayTimeLimit" class="input" min="1">
                <label>分钟</label>
              </div>
            </div>
          </div>
          <div class="mt-6 flex justify-end space-x-2">
            <button @click="closeHandleDialog" class="btn btn-secondary">取消</button>
            <button @click="saveHandleSettings" class="btn btn-primary">确认</button>
          </div>
        </div>
      </div>
    </Teleport> -->
    <el-dialog class="dialog-from dialog-set" v-model="isHandleDialogOpen" title="异常行为报警规则设置" width="600"
      destroy-on-close align-center>
      <div class="body-set-item">
        <div class="box-title">
          <div class="box-set-color"></div><strong>身份验证失败报警</strong>
        </div>
        <div class="box-content-item">
          <span>触发条件： 失败尝试次数限制：</span> <el-input class="set-input" type="number"
            v-model="handleSettings.failureAttempts" style="width: 30px; height: 30px;font-size: 12px;"
            :disabled="radio1 == '关闭'" /> <span>次</span>
          <div style="margin-top: 5px;">
            <span>通知对象：<el-select class="set-select" v-model="handleSettings.frequentTimes" placeholder="请选择"
                :disabled="radio2 == '关闭'">
                <el-option label="值班A组-张三" value="值班A组-张三" />
              </el-select></span>
          </div>
        </div>
        <div class="box-content-item">
          <el-radio-group v-model="radio1">
            <el-radio value="启用" size="small">启用</el-radio>
            <el-radio value="关闭" size="small">关闭</el-radio>
          </el-radio-group>
        </div>
      </div>
      <el-divider class="set-der" />
      <div class="body-set-item">
        <div class="box-title">
          <div class="box-set-color"></div><strong>不按规定时间进出报警</strong>
        </div>
        <div class="box-content-item">
          <span>触发条件： 设置禁止进出时间段： 从 </span><input type="datetime-local" v-model="handleSettings.frequentTimes"
            class="input-time mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
            :disabled="radio4 == '关闭'" /> 到 <input type="datetime-local" v-model="handleSettings.frequentTimes"
            class="input-time mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
            :disabled="radio4 == '关闭'" />
          <div style="margin-top: 5px;">
            <span>通知对象：<el-select class="set-select" v-model="handleSettings.frequentTimes" placeholder="请选择"
                :disabled="radio2 == '关闭'">
                <el-option label="值班A组-张三" value="值班A组-张三" />
              </el-select></span>
          </div>
        </div>
        <div class="box-content-item">
          <el-radio-group v-model="radio1">
            <el-radio value="启用" size="small">启用</el-radio>
            <el-radio value="关闭" size="small">关闭</el-radio>
          </el-radio-group>
        </div>
      </div>
      <el-divider class="set-der" />
      <div class="body-set-item">
        <div class="box-title">
          <div class="box-set-color"></div><strong>频繁进出报警</strong>
        </div>
        <div class="box-content-item">
          <span>触发条件： 设定频繁进出时间窗口： </span><el-input class="set-input" type="number"
            v-model="handleSettings.failureAttempts" style="width: 30px; height: 30px;font-size: 12px;"
            :disabled="radio1 == '关闭'" /> 分钟之内超过 <el-input class="set-input" type="number"
            v-model="handleSettings.failureAttempts" style="width: 30px; height: 30px;font-size: 12px;"
            :disabled="radio1 == '关闭'" />次
          <div style="margin-top: 5px;">
            <span>通知对象：<el-select class="set-select" v-model="handleSettings.frequentTimes" placeholder="请选择"
                :disabled="radio2 == '关闭'">
                <el-option label="值班A组-张三" value="值班A组-张三" />
              </el-select></span>
          </div>
        </div>
        <div class="box-content-item">
          <el-radio-group v-model="radio1">
            <el-radio value="启用" size="small">启用</el-radio>
            <el-radio value="关闭" size="small">关闭</el-radio>
          </el-radio-group>
        </div>
      </div>
      <el-divider class="set-der" />
      <div class="body-set-item">
        <div class="box-title">
          <div class="box-set-color"></div><strong>停留异常报警</strong>
        </div>
        <div class="box-content-item">
          <span>触发条件： 停留时间上限： </span><el-input class="set-input" type="number" v-model="handleSettings.failureAttempts"
            style="width: 30px; height: 30px;font-size: 12px;" :disabled="radio1 == '关闭'" /> 分钟
          <div style="margin-top: 5px;">
            <span>通知对象：<el-select class="set-select" v-model="handleSettings.frequentTimes" placeholder="请选择"
                :disabled="radio2 == '关闭'">
                <el-option label="值班A组-张三" value="值班A组-张三" />
              </el-select></span>
          </div>
        </div>
        <div class="box-content-item">
          <el-radio-group v-model="radio1">
            <el-radio value="启用" size="small">启用</el-radio>
            <el-radio value="关闭" size="small">关闭</el-radio>
          </el-radio-group>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="isHandleDialogOpen = false">确认</el-button>
          <el-button @click="isHandleDialogOpen = false">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Add Incident Dialog -->
    <Teleport to="body">
      <div v-if="isAddDialogOpen"
        class="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
        <div class="bg-card text-card-foreground p-5 rounded-lg shadow-xl w-[800px]">
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-bold">新增异常行为报警</h3>
            <button @click="closeAddDialog" class="text-muted-foreground hover:text-foreground">
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"
                xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>
          <form @submit.prevent="addNewIncident">
            <div class="grid grid-cols-2 gap-4">
              <div>
                <label for="incident_code" class="block text-sm font-medium text-muted-foreground">事件编码：</label>
                <input type="text" id="incident_code" v-model="newIncident.incident_code" required class="input">
              </div>
              <div>
                <label for="incident_type" class="block text-sm font-medium text-muted-foreground">事件类型：</label>
                <select id="incident_type" v-model="newIncident.incident_type" required class="input">
                  <option value="一般事件">一般事件</option>
                  <option value="紧急事件">紧急事件</option>
                  <option value="重大事件">重大事件</option>
                </select>
              </div>
              <div>
                <label for="description" class="block text-sm font-medium text-muted-foreground">事件描述：</label>
                <textarea id="description" v-model="newIncident.description" required class="input"></textarea>
              </div>
              <div>
                <label for="occurrence_time" class="block text-sm font-medium text-muted-foreground">发生时间：</label>
                <input type="datetime-local" id="occurrence_time" v-model="newIncident.occurrence_time" required
                  class="input">
              </div>
              <div>
                <label for="status" class="block text-sm font-medium text-muted-foreground">处理状态：</label>
                <select id="status" v-model="newIncident.status" required class="input">
                  <option value="未处理">未处理</option>
                  <option value="处理中">处理中</option>
                  <option value="已处理">已处理</option>
                </select>
              </div>
              <div>
                <label class="flex items-center space-x-2">
                  <input type="checkbox" v-model="newIncident.id_card_failure_alarm" class="checkbox">
                  <span class="text-sm font-medium text-muted-foreground">身份验证失败报警</span>
                </label>
              </div>
              <div>
                <label for="failure_attempts" class="block text-sm font-medium text-muted-foreground">失败尝试次数限制：</label>
                <input type="number" id="failure_attempts" v-model="newIncident.failure_attempts" min="1" class="input">
              </div>
              <div>
                <label class="flex items-center space-x-2">
                  <input type="checkbox" v-model="newIncident.time_restriction_alarm" class="checkbox">
                  <span class="text-sm font-medium text-muted-foreground">不按规定时间进出报警</span>
                </label>
              </div>
              <div>
                <label for="restricted_start_time"
                  class="block text-sm font-medium text-muted-foreground">禁止进出开始时间：</label>
                <input type="time" id="restricted_start_time" v-model="newIncident.restricted_start_time" class="input">
              </div>
              <div>
                <label for="restricted_end_time"
                  class="block text-sm font-medium text-muted-foreground">禁止进出结束时间：</label>
                <input type="time" id="restricted_end_time" v-model="newIncident.restricted_end_time" class="input">
              </div>
              <div>
                <label class="flex items-center space-x-2">
                  <input type="checkbox" v-model="newIncident.frequent_access_alarm" class="checkbox">
                  <span class="text-sm font-medium text-muted-foreground">频繁进出报警</span>
                </label>
              </div>
              <div>
                <label for="frequent_interval"
                  class="block text-sm font-medium text-muted-foreground">频繁进出时间间隔(分钟)：</label>
                <input type="number" id="frequent_interval" v-model="newIncident.frequent_interval" min="1"
                  class="input">
              </div>
              <div>
                <label for="frequent_times" class="block text-sm font-medium text-muted-foreground">频繁进出次数：</label>
                <input type="number" id="frequent_times" v-model="newIncident.frequent_times" min="1" class="input">
              </div>
              <div>
                <label class="flex items-center space-x-2">
                  <input type="checkbox" v-model="newIncident.long_stay_alarm" class="checkbox">
                  <span class="text-sm font-medium text-muted-foreground">停留异常报警</span>
                </label>
              </div>
              <div>
                <label for="stay_time_limit" class="block text-sm font-medium text-muted-foreground">停留时间上限(分钟)：</label>
                <input type="number" id="stay_time_limit" v-model="newIncident.stay_time_limit" min="1" class="input">
              </div>
            </div>
            <div class="mt-4 flex justify-end space-x-2">
              <button type="button" @click="closeAddDialog" class="btn btn-secondary">取消</button>
              <button type="submit" class="btn btn-primary">确认</button>
            </div>
          </form>
        </div>
      </div>
    </Teleport>

    <!-- Edit Incident Dialog -->
    <Teleport to="body">
      <div v-if="isEditDialogOpen"
        class="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
        <div class="bg-card text-card-foreground p-5 rounded-lg shadow-xl w-[800px]">
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-bold">编辑异常行为报警</h3>
            <button @click="closeEditDialog" class="text-muted-foreground hover:text-foreground">
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"
                xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>
          <form @submit.prevent="updateIncident">
            <div class="grid grid-cols-2 gap-4">
              <div>
                <label for="editCode" class="block text-sm font-medium text-muted-foreground">事件编码：</label>
                <input type="text" id="editCode" v-model="editingIncident.code" required class="input">
              </div>
              <div>
                <label for="editType" class="block text-sm font-medium text-muted-foreground">事件类型：</label>
                <select id="editType" v-model="editingIncident.type" required class="input">
                  <option value="一般事件">一般事件</option>
                  <option value="紧急事件">紧急事件</option>
                  <option value="重大事件">重大事件</option>
                </select>
              </div>
              <div>
                <label for="editDescription" class="block text-sm font-medium text-muted-foreground">事件描述：</label>
                <textarea id="editDescription" v-model="editingIncident.description" required class="input"></textarea>
              </div>
              <div>
                <label for="editTime" class="block text-sm font-medium text-muted-foreground">发生时间：</label>
                <input type="datetime-local" id="editTime" v-model="editingIncident.time" required class="input">
              </div>
            </div>
            <div class="mt-4 flex justify-end space-x-2">
              <button type="button" @click="closeEditDialog" class="btn btn-secondary">取消</button>
              <button type="submit" class="btn btn-primary">确认</button>
            </div>
          </form>
        </div>
      </div>
    </Teleport>

    <!-- View Incident Details Dialog -->
    <Teleport to="body">
      <div v-if="isViewDialogOpen"
        class="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
        <div class="bg-card text-card-foreground p-5 rounded-lg shadow-xl w-[800px]">
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-bold">查看异常行为报警详情</h3>
            <button @click="closeViewDialog" class="text-muted-foreground hover:text-foreground">
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"
                xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>
          <div class="grid grid-cols-2 gap-4">
            <div v-for="(value, key) in viewingIncident" :key="key" class="mb-2">
              <strong>{{ getChineseFieldName(key) }}:</strong> {{ value }}
            </div>
          </div>
          <div class="flex justify-center mt-4">
            <button @click="closeViewDialog" class="btn btn-secondary">关闭</button>
          </div>
        </div>
      </div>
    </Teleport>

    <!-- Import Dialog -->
    <Teleport to="body">
      <div v-if="isImportDialogOpen"
        class="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
        <div class="bg-card text-card-foreground p-5 rounded-lg shadow-xl w-[400px]">
          <h3 class="text-lg font-bold mb-4">导入异常行为报警记录</h3>
          <input accept=".csv, .xlsx" class="mb-4 block w-full text-sm text-muted-foreground
            file:mr-4 file:py-2 file:px-4
            file:rounded-full file:border-0
            file:text-sm file:font-semibold
            file:bg-primary file:text-primary-foreground
            hover:file:bg-primary/80" type="file" @change="handleFileUpload" />
          <div class="flex justify-end">
            <button class="btn btn-primary mr-2" @click="importData">
              导入
            </button>
            <button class="btn btn-secondary" @click="closeImportDialog">
              取消
            </button>
          </div>
        </div>
      </div>
    </Teleport>
  </div>
</template>


<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { getCurrentInstance } from 'vue'
import * as XLSX from 'xlsx'
import { ElSelect, ElOption } from 'element-plus'
const { proxy } = getCurrentInstance()

const apiBaseUrl = ref(proxy.$currentUrl + '/api/abnormal-behavior')

const search = ref({
  CAR_PERSON: '',
  START_TIME: '',
  END_TIME: ''
})

const tableHeaders = ['序号', '事件描述', '车辆/人员详情', '抓拍画面', '视频', '发生日期']
const options = [
  {
    value: '特殊事件',
    label: '一般事件',
  },
  {
    value: '特殊事件',
    label: '特殊事件',
  },
]
const incidentData = ref([])
const allChecked = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)

const isAddDialogOpen = ref(false)
const isImportDialogOpen = ref(false)
const isEditDialogOpen = ref(false)
const isViewDialogOpen = ref(false)
const isHandleDialogOpen = ref(false)

const newIncident = ref({
  incident_code: '',
  incident_type: '',
  description: '',
  occurrence_time: '',
  status: '未处理',
  id_card_failure_alarm: false,
  failure_attempts: 3,
  time_restriction_alarm: false,
  restricted_start_time: '',
  restricted_end_time: '',
  frequent_access_alarm: false,
  frequent_interval: 30,
  frequent_times: 3,
  long_stay_alarm: false,
  stay_time_limit: 120
})

const editingIncident = ref({})
const viewingIncident = ref({})

const handleSettings = ref({
  idCardFailure: false,
  failureAttempts: '',
  timeRestriction: false,
  startTime: '',
  endTime: '',
  frequentAccess: false,
  frequentInterval: 30,
  frequentTimes: 3,
  longStay: false,
  stayTimeLimit: 120
})
const radio1 = ref('启用')
const radio2 = ref('启用')
const radio3 = ref('启用')
const radio4 = ref('启用')

const totalItems = computed(() => incidentData.value.length)
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value))

const startIndex = computed(() => (currentPage.value - 1) * pageSize.value)
const endIndex = computed(() => Math.min(startIndex.value + pageSize.value, totalItems.value))

const displayedIncidentData = computed(() => {
  return incidentData.value.slice(startIndex.value, endIndex.value)
})

const searchIncidents = async () => {
  try {
    const response = await axios.get(`${apiBaseUrl.value}/search`, { params: search.value })
    incidentData.value = response.data.map(incident => ({ ...incident, checked: false }))
  } catch (error) {
    console.error('搜索异常行为报警记录失败:', error)
    alert('搜索异常行为报警记录失败: ' + (error.response?.data?.message || error.message))
  }
}

const resetSearch = () => {
  search.value = {
    CAR_PERSON: '',
    START_TIME: '',
    END_TIME: ''
  }
  searchIncidents()
}


const addNewIncident = async () => {
  try {
    const response = await axios.post(apiBaseUrl.value, newIncident.value)
    alert(response.data.message || '创建异常行为报警记录成功')
    closeAddDialog()
    await searchIncidents()
  } catch (error) {
    console.error('创建异常行为报警记录失败:', error)
    alert('创建异常行为报警记录失败: ' + (error.response?.data?.message || error.message))
  }
}

const deleteSelected = async () => {
  const selectedIds = incidentData.value.filter(incident => incident.checked).map(incident => incident.ID)
  if (selectedIds.length === 0) {
    alert('请选择要删除的记录')
    return
  }
  if (confirm(`确定要删除选中的 ${selectedIds.length} 条记录吗？`)) {
    try {
      await Promise.all(selectedIds.map(id => axios.delete(`${apiBaseUrl.value}/delete/${id}`)))
      alert('删除成功')
      await searchIncidents()
    } catch (error) {
      console.error('删除记录失败:', error)
      alert('删除记录失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

const updateIncident = async () => {
  try {
    const response = await axios.put(`${apiBaseUrl.value}/${editingIncident.value.id}`, editingIncident.value)
    alert(response.data.message || '更新异常行为报警记录成功')
    closeEditDialog()
    await searchIncidents()
  } catch (error) {
    console.error('更新异常行为报警记录失败:', error)
    alert('更新异常行为报警记录失败: ' + (error.response?.data?.message || error.message))
  }
}

const exportData = () => {
  const dataToExport = incidentData.value.map((expert) => ({
    '事件描述': expert.DESCRIPTION,
    '车辆/人员详情': expert.CAR_PERSON,
    '抓拍画面': expert.PASS_CORD,
    '视频': expert.PASS_TV ? expert.PASS_TV : '无',
    '发生日期': formatDateTime(expert.TIME_BEGIN),
  }))

  const worksheet = XLSX.utils.json_to_sheet(dataToExport)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, "异常行为报警")
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
  const data = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
  const link = document.createElement('a')
  link.href = window.URL.createObjectURL(data)
  link.download = '异常行为报警数据.xlsx'
  link.click()
}

const importFile = ref(null)

const handleFileUpload = (event) => {
  importFile.value = event.target.files[0]
}

const importData = async () => {
  if (!importFile.value) {
    alert('请选择要导入的文件')
    return
  }
  const formData = new FormData()
  formData.append('file', importFile.value)
  try {
    const response = await axios.post(`${apiBaseUrl.value}/import`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    alert(response.data.message || '导入成功')
    closeImportDialog()
    await searchIncidents()
  } catch (error) {
    console.error('导入失败:', error)
    alert('导入失败: ' + (error.response?.data?.message || error.message))
  }
}

const openAddDialog = () => {
  isAddDialogOpen.value = true
  newIncident.value = {
    incident_code: '',
    incident_type: '',
    description: '',
    occurrence_time: '',
    status: '未处理',
    id_card_failure_alarm: false,
    failure_attempts: 3,
    time_restriction_alarm: false,
    restricted_start_time: '',
    restricted_end_time: '',
    frequent_access_alarm: false,
    frequent_interval: 30,
    frequent_times: 3,
    long_stay_alarm: false,
    stay_time_limit: 120
  }
}

const closeAddDialog = () => {
  isAddDialogOpen.value = false
  newIncident.value = {
    incident_code: '',
    incident_type: '',
    description: '',
    occurrence_time: '',
    status: '未处理',
    id_card_failure_alarm: false,
    failure_attempts: 3,
    time_restriction_alarm: false,
    restricted_start_time: '',
    restricted_end_time: '',
    frequent_access_alarm: false,
    frequent_interval: 30,
    frequent_times: 3,
    long_stay_alarm: false,
    stay_time_limit: 120
  }
}

const openImportDialog = () => {
  isImportDialogOpen.value = true
}

const closeImportDialog = () => {
  isImportDialogOpen.value = false
  importFile.value = null
}

const editIncident = (incident) => {
  editingIncident.value = { ...incident }
  isEditDialogOpen.value = true
}

const closeEditDialog = () => {
  isEditDialogOpen.value = false
  editingIncident.value = {}
}

const viewDetails = (incident) => {
  viewingIncident.value = { ...incident }
  isViewDialogOpen.value = true
}

const closeViewDialog = () => {
  isViewDialogOpen.value = false
  viewingIncident.value = {}
}

const openHandleDialog = () => {
  isHandleDialogOpen.value = true
}

const closeHandleDialog = () => {
  isHandleDialogOpen.value = false
}

const saveHandleSettings = () => {
  // 这里可以添加保存设置的逻辑
  console.log('保存设置:', handleSettings.value)
  closeHandleDialog()
}

const toggleAllCheckboxes = () => {
  allChecked.value = !allChecked.value
  incidentData.value.forEach(incident => incident.checked = allChecked.value)
}

const prevPage = () => {
  if (currentPage.value > 1) currentPage.value--
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) currentPage.value++
}

const goToPage = (page) => {
  currentPage.value = page
}

const getChineseFieldName = (key) => {
  const fieldNameMap = {
    code: '事件编码',
    type: '事件类型',
    description: '事件描述',
    time: '发生时间'
  }
  return fieldNameMap[key] || key
}

const formatDateTime = (datetime) => {
  return new Date(datetime).toLocaleString()
}

const formatTime = (time) => {
  return time ? new Date(time).toLocaleTimeString() : '无'
}

const value = ref('')


const formItems = ref([
  {
    label: '事件编码：',
    model: 'code',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '事件类型：',
    model: 'type',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '请选择', value: '' },
      { label: '一般事件', value: '一般事件' },
      { label: '紧急事件', value: '紧急事件' },
      { label: '重大事件', value: '重大事件' },
    ],
  },
]);

onMounted(() => {
  searchIncidents()
})



</script>

<style scoped>
.input {
  @apply mt-1 block w-full rounded-md border-input bg-background px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring;
}

.btn {
  @apply px-4 py-2 rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition duration-150 ease-in-out;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}

.checkbox {
  @apply h-4 w-4 text-primary focus:ring-primary border-input rounded;
}

.table-header {
  @apply px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider;
}

.table-cell {
  @apply px-6 py-4 whitespace-nowrap text-sm;
}

.btn-pagination {
  @apply relative inline-flex items-center px-4 py-2 border border-border text-sm font-medium;
}

.action-button {
  @apply text-primary hover:text-primary/80 px-2 py-1 rounded;
}

.clselect {
  display: flex;
  margin-top: 10px;
  align-items: center;
}
</style>
<style scoped>
.query-form-inline :deep(.el-form-item) {
  margin-bottom: 0;
}

.query-form-inline :deep(.el-form-item .el-select) {
  width: 180px;
}

.query-btns {
  float: right;
}

.input-time {
  display: inline-block;
  border-radius: 4px;
  margin-top: 0;
  box-shadow: 0 0 0 1px #dcdfe6;
}

.input-time:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}
</style>
<style lass="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  /* 按钮居中对齐 */
}

.total-num {
  color: #02a7f0;
  font-size: 28px;
}

:deep(.dialog-from.el-dialog) {
  padding-top: 0;
  padding-left: 0;
  padding-right: 0;
}

:deep(.dialog-from .el-dialog__header) {
  padding: 11px 17px;
  background-color: #f2f2f2;
  font-size: 18px;
}

.dialog-from :deep(.el-dialog__body) {
  padding-left: 48px;
  padding-right: 48px;
  padding-top: 20px;
}

.body-item {}



.box-title {
  margin-bottom: 10px;
}

.box-color {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: #027db4;
  margin-right: 10px;
}



.box-content {
  /* height: 80px; */
}

.row-item {
  height: 80px;
  /* margin-bottom: 20px; */
}

.input-time {
  display: inline-block;
  border-radius: 0;
  margin-top: 0;
  box-shadow: 0 0 0 1px #dcdfe6;
  width: 120px;
  height: 25px;
}

.input-time:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.input-time-query {
  margin-top: 0;
  border-radius: 5%;
  display: inline-block;
  box-shadow: 0 0 0 1px #dcdfe6;
  width: 180px;
  height: 32px;
}

.input-time-query:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.upload-demo {
  position: relative;
  display: inline-block;
  width: 100%;
}

.upload-demo :deep(.el-upload) {
  width: 100%;
}

.input-upload {
  width: 100%;
}

:deep(.dialog-set .el-dialog__body) {
  padding: 0 27px;
}

.body-set-item {
  margin-top: 20px;
  padding: 0 31px;
}

.box-set-color {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #02A7F0;
  margin-right: 10px;
}

.box-content-item {
  margin-top: 5px;
  padding-left: 20px;
  font-size: 12px;
}

:deep(.set-input .el-input__wrapper) {
  padding: 0;
  border-radius: 0;
}

:deep(.set-input .el-input__wrapper .el-input__inner) {
  text-align: center;
}

.set-select {
  width: 120px;
}

:deep(.set-select .el-select__wrapper) {
  font-size: 12px;
  padding: 0 5px 0 0;
  text-align: center;
  border-radius: 0;
}
</style>
